#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pygame
import random

# 初始化Pygame
pygame.init()

# 屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("坦克大战")

# 时钟
clock = pygame.time.Clock()

# 坦克类
class Tank(pygame.sprite.Sprite):
    def __init__(self, color, x, y):
        super().__init__()
        self.image = pygame.Surface((40, 40))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = 5

    def move(self, dx, dy):
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed
        # 防止坦克移出屏幕
        self.rect.x = max(0, min(self.rect.x, SCREEN_WIDTH - self.rect.width))
        self.rect.y = max(0, min(self.rect.y, SCREEN_HEIGHT - self.rect.height))

# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction):
        super().__init__()
        self.image = pygame.Surface((10, 10))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.direction = direction
        self.speed = 10

    def update(self):
        self.rect.x += self.direction[0] * self.speed
        self.rect.y += self.direction[1] * self.speed
        # 如果子弹飞出屏幕，则删除
        if self.rect.right < 0 or self.rect.left > SCREEN_WIDTH or self.rect.bottom < 0 or self.rect.top > SCREEN_HEIGHT:
            self.kill()

# 创建玩家坦克
player_tank = Tank(GREEN, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 50)

# 创建敌人坦克
enemy_tank = Tank(BLACK, SCREEN_WIDTH // 2, 50)

# 创建精灵组
all_sprites = pygame.sprite.Group()
all_sprites.add(player_tank)
all_sprites.add(enemy_tank)

bullets = pygame.sprite.Group()

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # 发射子弹
                bullet = Bullet(player_tank.rect.centerx, player_tank.rect.centery, (0, -1))
                all_sprites.add(bullet)
                bullets.add(bullet)

    # 获取按键状态
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player_tank.move(-1, 0)
    if keys[pygame.K_RIGHT]:
        player_tank.move(1, 0)
    if keys[pygame.K_UP]:
        player_tank.move(0, -1)
    if keys[pygame.K_DOWN]:
        player_tank.move(0, 1)

    # 更新子弹
    bullets.update()

    # 检测子弹与敌人坦克的碰撞
    hits = pygame.sprite.spritecollide(enemy_tank, bullets, True)
    if hits:
        print("敌人坦克被击中!")
        enemy_tank.kill()

    # 渲染
    screen.fill(WHITE)
    all_sprites.draw(screen)
    pygame.display.flip()

    # 控制帧率
    clock.tick(30)

# 退出游戏
pygame.quit()




